/**
 * @description: 数据中台-任务-任务管理
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import Container from '@icedesign/container';
import styles from './index.module.scss';
import event from '@/request'
import {Button, Dialog, Input, Message, Pagination, Table} from '@alifd/next';
import ZgDialog from '@/components/ZgDialog';
import $http from '@/service/Services';
import AuthButton from "../../../components/AuthComponent/AuthBotton";


/**
 * list
 */
class NodeList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            subjectId: '',
            current: 0,
            mockData: [],
            selectedList: [],
            condition: '',
            config: {
                data: null,
                visible: false,
                title: '',
                content: ''
            }
        };
        this.pageNum = 1; // 当前页数
        this.pageSize = 10; // 分页每页显示数据条数
        this.totalNum = 0; // 数据总条数
        this.$http = $http;
        this.cancelCall = this.cancelCall.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.onPageChange = this.onPageChange.bind(this);
        this.getMonitorNodePageList = this.getMonitorNodePageList.bind(this);
        this.deleteEventTracking = this.deleteEventTracking.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        this.getMonitorNodePageList();
    };


    /**
     * 条件
     * @param e
     * @param value
     */
    searchCondition = (value, e) => {
        this.setState({
            condition: value,
            config: {
                data: null,
                visible: false,
                title: '',
                content: ''
            }
        });
        this.pageNum = 1;
    };
    /**
     * 改变页面
     * @param currentPage
     */
    onPageChange = (currentPage) => {
        this.state = {
            current: currentPage,
            mockData: this.props.mockData,
            config: {
                data: null,
                visible: false,
                title: '',
                content: ''
            }
        };
        this.getMonitorNodePageList();
    };
    /**
     * 分页大小改变执行
     * @param pageSize
     */
    onPageSizeChange =(pageSize)=>{
        this.pageSize = pageSize;
        this.pageNum = 1;
        this.getMonitorNodePageList();
    };
    /**
     * 修改分页数据
     * @param currentPage
     */
    onChangePage = (currentPage) => {
        this.setState({
            loading: true,
            config: {
                data: null,
                visible: false,
                title: '',
                content: ''
            }
        });
        setTimeout(() => {
            this.getMonitorNodePageList(currentPage);
            this.setState({
                loading: false,
                config: {
                    data: null,
                    visible: false,
                    title: '',
                    content: ''
                }
            });
        }, 0);
    };

    /**
     * 获取数据
     */
    getMonitorNodePageList = (pageNum) => {
        const _this = this;
        _this.pageNum = typeof (pageNum) == 'number' ? pageNum : _this.pageNum;
        let urls = event.event.url + '/v1/monitorNode/getMonitorNodePageList';
        this.$http.post(urls,
            {
                pageSize: _this.pageSize,
                pageNum: _this.pageNum,
                condition: {
                    name: _this.state.name,
                    address: _this.state.address
                }
            })
            .then(function (response) {
                const {data} = response;
                const mockData = data.data.voList;
                _this.totalNum = data.data.total;
                mockData.forEach((o, i) => {
                    o.number = i + 1;
                });

                _this.setState({
                    mockData: mockData,
                    config: {
                        data: null,
                        visible: false,
                        title: "",
                        content: ""
                    }
                });
            })
            .catch(function (error) {
                Message.error(error.message);
            })

    };


    /**
     * 删除
     */
    deleteEventTracking = (row) => {
        this.setState({
                config: {
                    data: row,
                    visible: true,
                    title: '提示消息',
                    content: '删除后不能恢复，确认要删除？'
                }
            }
        )
    };

    /**
     * 取消按钮的操作
     */
    cancelCall = () => {
        this.setState({
            config: {
                visible: false
            }
        });
    };


    /**
     * 删除
     */
    okCall = (data) => {
        this.setState({
            config: {
                visible: false
            }
        });
        const _this = this;
        this.$http.post(event.event.url + '/v1/monitorNode/deleteNodeById/'+ data.id)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success('操作成功.');
                    _this.getMonitorNodePageList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 批量删除
     * @param ids
     */
    handleSelect = (ids) => {
        const _this = this;
        this.$http.post(event.event.url + '/v1/task/deleteTask', {ids: ids})
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success('操作成功.');
                    _this.getMonitorNodePageList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };



    /**
     * start complete sync
     * @param record
     */
    changeStatus = (record) => {
        const _this = this;
        const urls = record.status == 0 ? event.event.url + '/v1/task/availability/' + record.id : event.event.url + '/v1/task/unavailable/' + record.id
        this.$http.post(urls)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success('操作成功.');
                    _this.getMonitorNodePageList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 批量操作
     * @param text
     */
    handleClick = () => {
        const {selectedList} = this.state;
        if (selectedList.length == 0) {
            Message.error('请选择需要删除的数据.');
            return null;
        }
        this.setState({
            visible: true
        });
    };

    /**
     *
     * @param args
     */
    onChange = (...args) => {
        this.setState({
            selectedList: args
        });
    };


    /**
     * 确定提示弹框
     */
    onOkDialog = () => {
        this.setState({
            visible: false
        });
        const {selectedList} = this.state;
        this.handleSelect(selectedList[1].map(o => {
            return o.id;
        }));
    };
    /**
     * 取消提示弹框
     */
    onCloseDialog = reason => {
        this.setState({
            visible: false
        });
    };


    render() {
        const {mockData} = this.state;
        return (
            <div>
                <div className='container-header'>
                    <p>节点管理</p>
                </div>
                <Container className='container-main'>
                    <div className='container-btnBox' style={{marginTop: '0'}}>
                        <div className={styles.buttons}>
                            <AuthButton auth={'DATA_CENTER$_METADATA$_ADD_METADATA'} type="normal" size="small"
                                        link={{to: 'node-add?id=', text: '新建节点'}}/>
                            <span className={styles.caseNumber}>
                                <Input onChange={this.searchCondition.bind(this)} placeholder={'节点名称/节点地址'}
                                       className={`${styles.input} ${styles.shortInput}`}/>

                                <Button
                                    type="primary"
                                    className='pipe-btn-search'
                                    onClick={this.getMonitorNodePageList}
                                >
                                查询
                                </Button>
                            </span>
                        </div>
                    </div>
                    <div className='container-table'>
                        <Table dataSource={mockData} size={'small'} primaryKey="id" className={styles.table}>
                            <Table.Column align="center" lock={"left"} title="序号" width={50} cell={
                                (value, index, record) => {
                                    return index + 1 + (this.pageNum - 1) * this.pageSize;
                                }
                            }/>
                            <Table.Column width={240} align="center" title="节点的名称" dataIndex="name"/>
                            <Table.Column width={240} align="center" title="分组" dataIndex="groupName"/>
                            <Table.Column width={240} align="center" title="地址" dataIndex="address"/>
                            <Table.Column width={80} align="center" title="协议" dataIndex="protocol"/>
                            <Table.Column width={150} align="center" title="节点的注册信息" dataIndex="nodeRegisterDateTime"/>
                            <Table.Column width={100} align="center" title="系统架构" dataIndex="nodeRegisterStatus" cell={
                                (value, index, record) => {
                                    if (value === 1){
                                        return (
                                            <span className="text-green">已注册</span>
                                        )
                                    }else if (value === 2){
                                        return (
                                            <span className="text-danger">超时</span>
                                        )
                                    }else {
                                        return (
                                            <span className="">未注册</span>
                                        )
                                    }
                                }
                            }/>
                            <Table.Column align="center" width={300} lock={"right"} title="操作" cell={
                                (value, index, record) => {
                                    return (
                                        <div>
                                            <AuthButton auth={'DATA_CENTER$_METADATA$_ADD_METADATA'} type="normal"
                                                        size="small"
                                                        link={{to: 'node-add?id=' + record.id, text: '修改'}}/>
                                            <AuthButton auth={'DATA_CENTER$_METADATA$_ADD_METADATA'} type="normal"
                                                        size="small"
                                                        link={{to: 'node-detail?nodeId=' + record.id, text: '详情'}}/>
                                            <AuthButton text auth={"RESPONSIVE$_DASHBOARD$_DELETE"} type="normal"
                                                        onClick={() => this.deleteEventTracking(record)} size="small"
                                                        title={"删除"}/>
                                        </div>
                                    )
                                }
                            }/>
                        </Table>
                        <ZgDialog config={this.state.config} cancelCall={this.cancelCall} okCall={this.okCall}/>
                        <Dialog
                            className='pipe-dialog'
                            title="提示信息"
                            visible={this.state.visible}
                            onOk={this.onOkDialog}
                            onCancel={this.onCloseDialog.bind(this, 'cancelClick')}
                            onClose={this.onCloseDialog}>
                            删除后不能恢复，确认要删除？
                        </Dialog>
                    </div>
                    {/**
                     * 分页
                     * defaultCurrent 初始页码
                     * total 总记录数
                     * pageSize 一页中的记录数
                     */}
                    <Pagination defaultCurrent={1}
                                pageSize={this.pageSize}
                                total={this.totalNum}
                                onPageSizeChange={this.onPageSizeChange}
                                pageSizeList={[5,10,20,50,100,200]}
                                pageSizeSelector="dropdown"
                                onChange={this.onChangePage}
                                className="page-demo"
                                size="small"
                    />
                </Container>
            </div>
        )
            ;
    }

}

export default NodeList;
